package com.jzo2o.foundations.service.impl;

import cn.hutool.core.bean.BeanUtil;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.SortOptions;
import co.elastic.clients.elasticsearch._types.SortOrder;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import com.jzo2o.common.utils.ObjectUtils;
import com.jzo2o.es.core.ElasticSearchTemplate;
import com.jzo2o.es.utils.SearchResponseUtils;
import com.jzo2o.foundations.model.domain.ServeAggregation;
import com.jzo2o.foundations.model.dto.response.ServeSimpleResDTO;
import com.jzo2o.foundations.service.ServeAggregationService;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author DarkClown
 * @date 2024-08-21 22:33
 * @project_name jzo2o-foundations
 * @parem
 **/
@Service
public class ServeAggregationServiceImpl implements ServeAggregationService {

    @Autowired
    private ServeServiceImpl serveService;

    @Autowired
    ElasticSearchTemplate elasticSearchTemplate;


    @Override
    public List<ServeSimpleResDTO> findServeList(String cityCode, Long serveTypeId, String keyword) {
        //构造查询条件
        SearchRequest.Builder builder = new SearchRequest.Builder();

        builder.query(query->query.bool(bool->{
            //匹配citycode
            bool.must(must->must.term(term->term.field("city_code").value(cityCode)));

            //匹配关键字
            if(ObjectUtils.isNotEmpty(keyword)){
                bool.must(must->
                    must.multiMatch(multiMatch->multiMatch.fields("serve_item_name","serve_type_name").query(keyword)));
                }
            return bool;

        }));
        //排序 按服务项的serveItemSortNum排序(升序)
        ArrayList<SortOptions> sortOptions = new ArrayList<>();
        sortOptions.add(SortOptions.of(sortOption->sortOption.field(field->field.field("serve_item_sort_num").order(SortOrder.Asc))));

        builder.sort(sortOptions);
        //指定索引
        builder.index("serve_aggregation");
        //请求对象
        SearchRequest searchRequest = builder.build();
        //检索数据
        SearchResponse<ServeAggregation> searchResponse = elasticSearchTemplate.opsForDoc().search(searchRequest, ServeAggregation.class);

        //如果搜索成功返回结果集
        if (SearchResponseUtils.isSuccess(searchResponse)){
            List<ServeAggregation> collect = searchResponse.hits().hits().stream().map(hit -> {
                ServeAggregation serve = hit.source();
                return serve;
            }).collect(Collectors.toList());
            List<ServeSimpleResDTO> serveSimpleResDTOS = BeanUtil.copyToList(collect, ServeSimpleResDTO.class);

            return serveSimpleResDTOS;
        }


        return Collections.emptyList();
    }
}
